package com.manor.main.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.manor.common.CommonAppConfig;
import com.manor.common.CommonAppContext;
import com.manor.common.Constants;
import com.manor.common.activity.BaseLocationActivity;
import com.manor.common.bean.UserBean;
import com.manor.common.em.AuthType;
import com.manor.common.event.AuthResultEvent;
import com.manor.common.event.LoginSuccessEvent;
import com.manor.common.http.JHttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.GsonUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.main.R;
import com.manor.main.bean.LoginBean;
import com.manor.main.http.JMainHttpUtil;
import com.manor.main.http.MainHttpUtil;
import com.manor.main.utils.CodeTimeCount;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * 验证码登录
 */
@Route(path = RouteUtil.PC_INPUT_SMSCODE)
public class InputSmsCodeActivity extends BaseLocationActivity implements View.OnClickListener {


    private android.widget.EditText mEtInputSmscode;
    private android.widget.TextView mTvCodesmsTime;
    private android.widget.TextView mTvErrorTips;
    private android.widget.TextView mTvLogin;
    @Autowired
    public String phone;
    private android.widget.TextView mTvInputphonesmscode;

    @Autowired
    public String smsCode;

    private boolean mFirstLogin;//是否是第一次登录.
    CodeTimeCount codeTimeCount;

    private String rePhone;
    private String reSmsCode;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_input_sms_code;
    }

    @Override
    protected void main() {
        super.main();
        ARouter.getInstance().inject(this);
        initView();
        initDate();
        sendMsgCode();
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();

    }

    private void initDate() {

        mEtInputSmscode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (mEtInputSmscode.getText().length() > 3) {
                    mTvLogin.setBackgroundResource(R.drawable.bg_get_codes);
                    mTvLogin.setClickable(true);
                    mTvLogin.setFocusable(true);
                } else {
                    mTvLogin.setBackgroundResource(R.drawable.bg_get_code);
                    mTvLogin.setClickable(false);
                    mTvLogin.setFocusable(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }


    private void initView() {
        mEtInputSmscode = findViewById(R.id.et_input_smscode);
        mTvCodesmsTime = findViewById(R.id.tv_codesms_time);
        mTvErrorTips = findViewById(R.id.tv_error_tips);
        mTvLogin = findViewById(R.id.tv_login);
        mTvInputphonesmscode = findViewById(R.id.tv_inputphonesmscode);
        mTvCodesmsTime.setOnClickListener(this);
        mTvLogin.setOnClickListener(this);

    }


    public static void forward() {
        Intent intent = new Intent(CommonAppContext.sInstance, InputSmsCodeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        CommonAppContext.sInstance.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tv_codesms_time) {
            //重新发送
            sendMsgCode();
        } else if (id == R.id.tv_login) {
            login();
        }
    }

    private final Handler handler = new Handler() {
        //接收handler发送的message
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            login();
        }
    };
    int sun = 0;

    /**
     * 登录
     */
    private void login() {
        String smscode = mEtInputSmscode.getText().toString();
        if ("".equals(smscode)) {
            ToastUtil.show("短信验证码不能为空");
            return;
        }

        if (npcCode == 0) {
            showWaitingDialog(false);
            if (sun >= 3) {
                // ToastUtil.show("无法获取您的位置，请走到开阔地带重试");
                dismissWaitingDialog();
                sun = 0;
            } else {
                handler.sendEmptyMessageDelayed(0, 1000);//发送消息
                sun++;
                return;
            }
        } else {
            dismissWaitingDialog();
        }

        mTvLogin.setSelected(false);
        showWaitingDialog(false);
        JMainHttpUtil.login(phone, smscode, npcCode, new JHttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                dismissWaitingDialog();
                if (code == 200) {
                    onMsgSuccess(code, msg, info);
                } else if (code == 1480) {//需要扫脸
                    KLog.e("JMainHttpUtil.login", info);
                    verifyFace(phone, smscode, info);
                } else {
                    ToastUtil.show(msg);
                    mTvLogin.setSelected(true);
                }
            }

            @Override
            public void onError() {
                super.onError();
                mTvLogin.setSelected(true);
                dismissWaitingDialog();
            }
        });
    }

    private void verifyFace(String phone, String smsCode, String info) {
        if (StringUtil.isEmpty(info))
            return;
        rePhone = phone;
        reSmsCode = smsCode;
        LoginBean bean = GsonUtil.gsonToBean(info, LoginBean.class);
        SpUtil.getInstance()
                .setStringValue(SpUtil.JAVA_TOKEN, bean.getTokenType() + " " + bean.getAccessToken());
        if (!this.isFinishing())
            setCamera();
    }

    private void reLogin() {
        if (StringUtil.isEmpty(rePhone) || StringUtil.isEmpty(reSmsCode))
            return;
        showWaitingDialog(false);
        mTvLogin.setSelected(false);
        JMainHttpUtil.login(rePhone, reSmsCode, npcCode, new JHttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                dismissWaitingDialog();
                if (code == 200) {
                    onMsgSuccess(code, msg, info);

                } else {
                    mTvLogin.setSelected(true);
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onError() {
                super.onError();
                dismissWaitingDialog();
                mTvLogin.setSelected(true);
            }
        });
    }


    private void setCamera() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA)//相机
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        RouteUtil.forwardFaceExp(AuthType.TYPE_LOGIN);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        ToastUtil.show(getResources().getString(R.string.permissions_camera));
                        if (AndPermission.hasAlwaysDeniedPermission(InputSmsCodeActivity.this, data)) {
                            InputSmsCodeActivity.this.showSettingDialog(InputSmsCodeActivity.this, getResources().getString(R.string.permissions_camera), 12);
                        } else {
                            setCamera();
                        }
                    }
                })
                .start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFaceResult(AuthResultEvent e) {
        if (e.getCode() == 200) {
            reLogin();
        } else {
            ToastUtil.show(e.getMsg());
        }
    }


    private void onMsgSuccess(int code, String msg, String info) {
        if (code == 200 && !info.equals("")) {

            LoginBean loginBean = GsonUtil.gsonToBean(info, LoginBean.class);
            parentSdNo = loginBean.getParentSdNo();
            SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, loginBean.getUsersig());
            MobclickAgent.onProfileSignIn(Constants.MOB_PHONE, loginBean.getUid());
            EventBus.getDefault().post(new LoginSuccessEvent());
            CommonAppConfig.getInstance().setLoginInfo(loginBean.getUid(), loginBean.getAccessToken(), true);
            SpUtil.getInstance().setStringValue(SpUtil.JAVA_TOKEN, loginBean.getTokenType() + " " + loginBean.getAccessToken());
            isFirstLogin(loginBean.getNikeName());
        } else {
            ToastUtil.show(msg);
        }
    }

    private void isFirstLogin(String name) {
        if ("".equals(name)) {
            //进入填写资料页面
            LoginGenderAgeActivity.forward(2);
        } else {
            //进入首页
            getBaseUserInfo();
        }

    }

    private void sendMsgCode() {
        codeTimeCount = new CodeTimeCount(59000, 1000, mTvCodesmsTime);
        codeTimeCount.start();
        showWaitingDialog(false);
        JMainHttpUtil.JloginCode(phone, new JHttpCallback() {

            @Override
            public void onError() {
                super.onError();
                ToastUtil.show("服务器返回错误");
                dismissWaitingDialog();
            }

            @Override
            public void onSuccess(int code, String msg, String info) {
                dismissWaitingDialog();
                if (code == 200) {
                    mTvInputphonesmscode.setText("验证码已通过短信发送至+86 " + phone);
                } else if (code == 400) {
                    mTvInputphonesmscode.setText("验证码已发送至+86 " + phone);
                } else {
                    ToastUtil.show(msg);
                    codeTimeCount.cancel();
                    codeTimeCount.onFinish();
                }
            }
        });


    }


    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                MainActivity.Companion.forward(mContext, mFirstLogin);
            }
        });
    }


}
